import Taro, { Component } from '@tarojs/taro';
import { View, Image, Text } from '@tarojs/components';
import { AtTextarea } from 'taro-ui'
import { DNavBar, DCheckOpinion, DLookImages, DImagesupload } from '@/components';
import './index.scss';
import http from '@/api'

export default class BuyCheckDetail extends Component {
  state = {
    moneyIcon: require('@/assets/images/money_icon.png'),
    carIcon: require('@/assets/images/car_icon.png'),
    fileIcon: require('@/assets/images/file_icon.png'),
    detail: {},    // 详情
    basicInfo: [], // 基本信息列表
    carInfo: [],   // 车辆信息列表
    superviseInfo: [], // 监管信息
    reviewFiles: [], // 验车资料
    previewImg: {
      itemStatus: false,
      itemUrl: ''
    },
    $imgUploadChild: null,
    imgCheckList: [],
    explain: ''
  }

  componentDidMount() {
    this.getBuyDetail()
  }

  async getBuyDetail() {
    const detail = await http.getBuyDetail(this.$router.params.id)
    this.handlerBasicInfo(detail)
    this.handlerCarInfo(detail)
    this.handleSuperviseInfo(detail)
    this.setState({ detail })
  }
  // 处理基本信息
  handlerBasicInfo(detail = {}) {
    const basicInfoMap = {
      'orderNo': '代购编号',
      'contact': '申请账号',
      'entName': '申请人公司',
      'createTime': '申请日期',
      'vehicleOwnerName': '车主姓名',
      'amTailMoneyComp': '尾帐进账公司',
      'amSpendPeriod': '用款天数',
      'amSpendDate': '用款日期',
      'amCarType': '选择车型',
      'amMoney': '代购金额',
      'amContractMoney': '合同金额',
      'downPayment': '首付款金额'
    }
    let basicInfo = []
     Object.keys(basicInfoMap).forEach(key => {
      let value = detail[key]
      if (['amMoney', 'amContractMoney', 'downPayment'].includes(key)) {
        value += '万'
      }
      if (key === 'amSpendPeriod') {
        value += '天'
      }
      basicInfo.push({
        label: basicInfoMap[key],
        value: value || '---'
      })
    })
    this.setState({ basicInfo })
  }
  // 处理车辆信息
  handlerCarInfo(detail = {}) {
    const carInfoMap = {
      'amCarOutColor': '外观颜色',
      'amCarInColor': '内饰颜色',
      'amCarNo': '车架号',
      'amLogisStart': '物流始发地',
      'amLogisEnd': '物流目的地'
    }
    let carInfo = []
    Object.keys(detail).forEach(key => {
      if (carInfoMap[key]) {
        carInfo.push({
          label: carInfoMap[key],
          value: detail[key] || '---'
        })
      }
    })
    this.setState({ carInfo })
  }
  // 处理监管信息
  handleSuperviseInfo({ applyFiles }) {
    const fileTypeMap = {
      1: '车主身份证',
      2: '采购合同',
      3: '定金支付凭证',
      4: '付款凭证',
      5: '按揭凭证',
      6: '订金合同',
      7: '同贷信息',
      8: '审核表',
      9: '确认书',
      11: '付款路径图',
      12: '其他'
    }
    let tempObj = {}, superviseInfo = []

    applyFiles.forEach(item => {
      if (tempObj[item.afFileType]) {
        tempObj[item.afFileType].push(item)
      } else {
        tempObj[item.afFileType] = [item]
      }
    })

    Object.keys(fileTypeMap).forEach(key => {
      superviseInfo.push({
        label: fileTypeMap[key],
        list: tempObj[key]
      })
    })

    let reviewFiles = applyFiles.filter(item => item.afBusstype === '1')

    this.setState({ superviseInfo, reviewFiles })
  }
  // 计算tag标签类名
  computedTagClass(status) {
    const tagStatusMap = {
      6: 'blue',
    }
    return tagStatusMap[status] || 'orange'
  }
  computedCheckTitle = (status) => {
    return {
      0: '审核',
      11: '财务确认',
    }[status]
  }
  computedCheckOpinions = (status) => {
    return {
      0: [{
        name: '审核通过',
        value: 'success'
      }, {
        name: '审核不通过',
        value: 'fail'
      }],
      11: [{
        name: '通过',
        value: 'success'
      }, {
        name: '不通过',
        value: 'fail'
      }]
    }[status]
  }
  onLookHandle(url) {
    if (window.bridge) {
      let _images = [], i = 0
      _images.push(url)
      window.bridge.callHandler('previewPhoto', { "index": i, "images": _images }, function responseCallback() { })
    } else {
      this.setState({
        previewImg: {
          itemStatus: true,
          itemUrl: url
        }
      })
    }
  }
  onLookItem() {
    this.setState({
      previewImg: {
        ...this.state.previewImg,
        itemStatus: false,
        itemUrl: ''
      }
    })
  }
  // 返回上一个页面
  goBack = () => {
    Taro.navigateBack()
  }
  // 财务确认打款
  confirmRemit = () => {
    Taro.showModal({
      title: '提示',
      content: '财务确认打款。此操作不可逆，请谨慎操作。',
      success: ({ confirm }) => {
        if (confirm) {
          http.contractConfirm(this.state.detail.id).then(() => {
            Taro.showToast({
              title: '操作成功',
              icon: 'success',
            })
            setTimeout(() => {Taro.navigateBack()}, 2000)
          })
        }
      }
    })
  }
  // 审核操作
  handleConfirm = ({ checkOpinion, explain }) => {
    const { status, id } = this.state.detail
    let tipMessage = status === '11' ? '财务确认操作！此操作不可逆，请谨慎操作！' : '是否确认该操作'

    Taro.showModal({
      title: '提示',
      content: tipMessage,
      success: ({ cancel, confirm }) => {
        if (confirm) {
          let checkHttp, params = { id }
          if (status === '0') {
            // 审核
            checkHttp = checkOpinion === 'success' ? http.MoneyApplyPass : http.MoneyApplyNoPass
            checkOpinion === 'fail' && (params.auditOpinion = explain)
          } else if (status === '11') {
            // 财务确认
            checkHttp = checkOpinion === 'success' ? http.financePass : http.financeNoPass
            checkOpinion === 'fail' && (params.explain = explain)
          }

          checkHttp(params).then(() => {
            Taro.showToast({ title: '提交成功', icon: 'success' })
            setTimeout(() => {
              Taro.navigateBack()
            }, 2000);
          })
        }
      }
    })
  }
  updateReviewFiles = (e) => {
    this.state.$imgUploadChild.onHandleClick(e)
  }

  onChangeImages = (imgList) => {
    let list = imgList.map((item, index) => {
      let url = typeof item === 'string' ? item : item.url
      return {
        afBusstype: 1,
        afUrl: url,
        sort: index,
        refAmId: this.state.detail.id,
      }
    })
    http.imageUpload(list)
      .then(({ data }) => {
        Taro.showToast({
          title: '图片上传成功'
        })
        setTimeout(Taro.navigateBack, 200);
      })
  }
  handleChangeImg = (imgList) => {
    let list = imgList.map((item, index) => {
      let url = typeof item === 'string' ? item : item.url
      return {
        afBusstype: 1,
        afUrl: url,
        sort: index,
        refAmId: this.state.detail.id,
      }
    })

    this.setState({ imgCheckList: list })
  }
  FunCenter = (imgUploadChild) => {
    this.setState({
      $imgUploadChild: imgUploadChild
    })
  }
  submit = () => {
    let { imgCheckList, explain, detail } = this.state
    if (!imgCheckList.length) {
      // 没有上传图片
      http
        .imageUpload([{ afBusstype: 1, refAmId: detail.id }], explain )
        .then(() => {
          Taro.showToast({
            title: '验车成功'
          })
         setTimeout(Taro.navigateBack, 2000)
        })
    } else {
      http
        .imageUpload(imgCheckList, explain )
        .then(() => {
          Taro.showToast({
            title: '验车成功'
          })
         setTimeout(Taro.navigateBack, 2000)
        })
    }
  }

  render() {
    const { carIcon, fileIcon, detail, basicInfo, carInfo, superviseInfo, previewImg, reviewFiles, explain } = this.state;

    return (
      <View className="buy-check-detail">
        <DNavBar title="代购订单审核详情"></DNavBar>

        <View className="status_bar orange">{decodeURIComponent(this.$router.params.statusDesc)}</View>

        <View className="info">
          <View className="title">
            <Image src={fileIcon} className="title_icon"></Image>
            <Text className="title_text">基本信息</Text>
          </View>
          {
            basicInfo.map(item => <View className="item">
              <View className="label">{item.label}</View>
              <View className={['value', item.label === '代购金额' ? 'red' : ''].join(' ')}>{item.value}</View>
            </View>)
          }


          <View className="border"></View>

          <View className="title">
            <Image src={carIcon} className="title_icon"></Image>
            <Text className="title_text">车辆信息</Text>
          </View>
          {
            carInfo.map(item => <View className="item">
              <View className="label">{item.label}</View>
              <View className="value">{item.value}</View>
            </View>)
          }

          <View className="border"></View>

          <View className="title">
            <Image src={carIcon} className="title_icon"></Image>
            <Text className="title_text">监管信息</Text>
          </View>
          {
            <View className="item">
              <View className="label">监管方式</View>
              <View className="value">{detail.amMonitorType}</View>
            </View>
          }
          {
            superviseInfo.map(item => (
              <View className="item">
                { item.list && <View className="label">{item.label}</View> }
                { item.list && <View className="value">
                  {
                    item.list.map(item => <Image className="photo" src={item.afUrl} onClick={this.onLookHandle.bind(this, item.afUrl)}></Image>)
                  }
                </View> }
              </View>)
            )
          }
        </View>

        <View className="border"></View>
        {/* 审核详情 */}
        {
            (detail.status == 11 || detail.status == 1 || detail.status == 13 || detail.status == 7 || detail.status == 12 || detail.status == 6) && <View className="check-detail">
            <View className="check-detail__title">审核</View>
            <View className="item">
              <View className="label">审核操作</View>
              <View className="value">{detail.status !== '7' ? '审核通过' : '审核不通过'}</View>
            </View>
            <View className="item">
              <View className="label">审核时间</View>
              <View className="value">{detail.updateTime1}</View>
            </View>
            <View className="item">
              <View className="label">审核人</View>
              <View className="value">{detail.updator1}</View>
            </View>
            <View className="item">
              <View className="label">审核原因</View>
              <View className="value">{decodeURIComponent(detail.explain1) || '无'}</View>
            </View>
          </View>
        }
        {/* 财务确认详情 */}
        {
          (detail.status == 1 || detail.status == 13 || detail.status == 12 || detail.status == 6) && <View className="check-detail">
            <View className="check-detail__title">财务确认</View>
            <View className="item">
              <View className="label">审核操作</View>
              <View className="value">{detail.status !== '12' ? '通过' : '不通过'}</View>
            </View>
            <View className="item">
              <View className="label">审核时间</View>
              <View className="value">{detail.updateTime2}</View>
            </View>
            <View className="item">
              <View className="label">审核人</View>
              <View className="value">{detail.updator2}</View>
            </View>
            <View className="item">
              <View className="label">审核原因</View>
              <View className="value">{decodeURIComponent(detail.explain2) || '无'}</View>
            </View>
          </View>
        }
        {/* 验车详情 */}
        {
          Boolean(reviewFiles.length) && <View className="check-detail">
            <View className="check-detail__title">验车</View>
            <View className="item">
              <View className="label">验车资料</View>
              <View className="value">已提交</View>
            </View>
            <View className="item">
              <View className="label">提交时间</View>
              <View className="value">{detail.updateTime3}</View>
            </View>
            <View className="item">
              <View className="label">提交人</View>
              <View className="value">{detail.updator3}</View>
            </View>
            <View className="item">
              <View className="label">验车说明</View>
              <View className="value">{decodeURIComponent(detail.explain3) || '无'}</View>
            </View>
            <View className="item">
              <View className="label">验车资料</View>
              <View className="value">
                {
                  reviewFiles.map(item => <Image className="photo" src={item.afUrl} onClick={this.onLookHandle.bind(this, item.afUrl)}></Image>)
                }
              </View>
            </View>
          </View>
        }

        {
          (detail.status === '0' || detail.status === '11') && <DCheckOpinion
            title={this.computedCheckTitle(detail.status)}
            label="审核操作"
            type="buy"
            opinions={this.computedCheckOpinions(detail.status)}
            onCancel={this.goBack}
            onConfirm={this.handleConfirm}
          />
        }

        {
          detail.status === '1' && <View className="upload_check_img">
            <View className="upload_check_img_title">上传验车</View>
            <View className="form">
              <View className="form_item">
                <View className="form_item_title">验车资料</View>
                <DImagesupload count={10} onChangeImages={this.handleChangeImg}></DImagesupload>
              </View>
              <View className="form_item">
                <View className="form_item_title">验车说明</View>
                <AtTextarea value={explain} onChange={(explain) => this.setState({ explain })}></AtTextarea>
              </View>
            </View>
          </View>
        }

        <View className="border"></View>

        {
          (detail.status === '1' || detail.status === '13' || detail.status === '6') && <View className="buttons">
            <View className="btn btn--cancel" onClick={this.goBack}>取消</View>
            {
              detail.status === '1' && <View className="btn btn--submit" onClick={this.submit}>上传验车</View>
            }
            {
              (detail.status === '13' || detail.status === '6') && <View className="btn btn--submit" onClick={this.updateReviewFiles}>上传验车</View>
            }
            {
              detail.status === '13' && <View className="btn btn--submit" onClick={this.confirmRemit}>确认打款</View>
            }
          </View>
        }

        <DImagesupload className="hide_upload" count={10} FunCenter={this.FunCenter} onChangeImages={this.onChangeImages}></DImagesupload>

        <DLookImages status={previewImg.itemStatus} url={previewImg.itemUrl} onLookHandle={this.onLookItem.bind(this)}></DLookImages>
      </View>
    )
  }
}
